package com.hkts.naturalgasauthentication.utils;

import cn.hutool.core.date.DateTime;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * @Package: com.wzy.util
 * @Author: Clarence1
 * @Date: 2019/10/4 20:17
 */
@Slf4j
@Component
public class FtpUtil {
    private static Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    /**
     * ftp服务器ip地址
     */
    private static String host;

    @Value("${ftp.host}")
    public void setHost(String val){
        FtpUtil.host = val;
    }

    /**
     * 端口
     */
    private static int port;

    @Value("${ftp.port}")
    public void setPort(int val){
        FtpUtil.port = val;
    }

    /**
     * 用户名
     */
    private static String userName;

    @Value("${ftp.userName}")
    public void setUserName(String val){
        FtpUtil.userName = val;
    }

    /**
     * 密码
     */
    private static String password;

    @Value("${ftp.password}")
    public void setPassword(String val){
        FtpUtil.password = val;
    }

    /**
     * 存放图片的根目录
     */
    private static String rootPath;

    @Value("${ftp.rootPath}")
    public void setRootPath(String val){
        FtpUtil.rootPath = val;
    }

    /**
     * 存放图片的路径
     */
    private static String imgUrl;

    @Value("${ftp.img.url}")
    public void setImgUrl(String val){
        FtpUtil.imgUrl = val;
    }
    /*@Autowired
    private DocumentConverter converter;*/
    //ffmpegpath
    private static String ffmpegpath;

    /*@Value("${ffmpegpath}")
    public void setFfmpegpath(String val){
        FtpUtil.ffmpegpath = val;
    }
    public  static  String  getFfmpegpath(){
        return ffmpegpath;
    }*/
    /**
     * 获取连接
     */
//获取临时文件路径
    private static String tempFilePath;
    @Value("${tempFilePath}")
    public void setTempFilePath(String val){
        FtpUtil.tempFilePath = val;
    }

    public  static  String  getTempFilePath(){
        return tempFilePath;
    }
    //get imgUrl
    public  static  String  getImgUrl(){
        return imgUrl;
    }
    private static ChannelSftp getChannel() throws Exception{

        JSch jsch = new JSch();

        //->ssh root@host:port
        Session sshSession = jsch.getSession(userName,host,port);
        //密码
        sshSession.setPassword(password);

        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect();

        Channel channel = sshSession.openChannel("sftp");
        channel.connect();

        return (ChannelSftp) channel;
    }
    //本地视频预览
    public static String localProcessPreview(String videoPath){
        String filePath = new DateTime().toString("/yyyyMMdd/");
        String uuid = UUID.randomUUID().toString();
        FFmpegFrameGrabber ff = null;
        String dataBack="";
        try {
            ff = new FFmpegFrameGrabber(videoPath);
            ff.start();
            int lenght = ff.getLengthInFrames();
            int i = 0;
            Frame f = null;
            while (i < lenght) {
                // 过滤前5帧，避免出现全黑的图片，依自己情况而定
                f = ff.grabFrame();
                if ((i > 5) && (f.image != null)) {
                    break;
                }
                i++;
            }

            int owidth = f.imageWidth ;
            int oheight = f.imageHeight ;
            // 对截取的帧进行等比例缩放
            int width = 800;
            int height = (int) (((double) width / owidth) * oheight);
            Java2DFrameConverter converter =new Java2DFrameConverter();
            BufferedImage fecthedImage =converter.getBufferedImage(f);
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
            bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    0, 0, null);
            /*bi.getGraphics().drawImage(f.image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    0, 0, null);*/
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            dataBack= putImages(input, filePath, uuid + ".jpg");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ff != null) {
                    ff.stop();
                }
            } catch (FrameGrabber.Exception e) {
                e.printStackTrace();
            }
        }
        return dataBack;
    }
    //处理视频预览图
    public static String processPreview(String videoPath){
        String filePath = new DateTime().toString("/yyyyMMdd/");
        String uuid = UUID.randomUUID().toString();
        FFmpegFrameGrabber ff = null;
        String dataBack="";
        try {
            String sss=imgUrl+videoPath;
            ff = new FFmpegFrameGrabber(imgUrl+videoPath);
            ff.start();
            int lenght = ff.getLengthInFrames();
            int i = 0;
            Frame f = null;
            while (i < lenght) {
                // 过滤前5帧，避免出现全黑的图片，依自己情况而定
                f = ff.grabFrame();
                if ((i > 5) && (f.image != null)) {
                    break;
                }
                i++;
            }

            int owidth = f.imageWidth ;
            int oheight = f.imageHeight ;
            // 对截取的帧进行等比例缩放
            int width = 800;
            int height = (int) (((double) width / owidth) * oheight);
            Java2DFrameConverter converter =new Java2DFrameConverter();
            BufferedImage fecthedImage =converter.getBufferedImage(f);
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
            bi.getGraphics().drawImage(fecthedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    0, 0, null);
            /*bi.getGraphics().drawImage(f.image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
                    0, 0, null);*/
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            dataBack= putImages(input, filePath, uuid + ".jpg");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (ff != null) {
                    ff.stop();
                }
            } catch (FrameGrabber.Exception e) {
                e.printStackTrace();
            }
        }
        return dataBack;
    }
    /**
     * ftp上传图片
     * @param inputStream 图片io流
     * @param imagePath 路径，不存在就创建目录
     * @param imagesName 图片名称
     * @return urlStr 图片的存放路径
     */
    public static String putImages(InputStream inputStream, String imagePath, String imagesName){
        try {
            ChannelSftp sftp = getChannel();
            String path = rootPath + imagePath + "/";
            createDir(path,sftp);

            //上传文件
            sftp.put(inputStream, path + imagesName);
            logger.info("上传成功！");
            sftp.quit();
            sftp.exit();

            //处理返回的路径
            String resultFile;
            resultFile = imagePath + imagesName;

            return resultFile;

        } catch (Exception e) {
            logger.error("上传失败：" + e.getMessage());
        }
        return "";
    }

    /**
     * 获取图片流
     * @param imagePath
     * @return
     */
    public static byte[] putImages( String imagePath) {
        byte[] data = null;
        try {
            ChannelSftp sftp = getChannel();
            String path = rootPath + imagePath;
            InputStream inputStream = sftp.get(path);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = inputStream.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 创建目录
     */
    private static void createDir(String path,ChannelSftp sftp) throws SftpException {
        String[] folders = path.split("/");
        sftp.cd("/");
        for ( String folder : folders ) {
            if ( folder.length() > 0 ) {
                try {
                    sftp.cd( folder );
                }catch ( SftpException e ) {
                    sftp.mkdir( folder );
                    sftp.cd( folder );
                }
            }
        }
    }

   /* public void initFtpClient() {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("utf-8");
        try {
            System.out.println("connecting...ftp服务器:"+this.host+":"+this.port);
            ftpClient.connect(host, port); //连接ftp服务器
            ftpClient.login(userName, password); //登录ftp服务器
            int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
            if(!FTPReply.isPositiveCompletion(replyCode)){
                System.out.println("connect failed...ftp服务器:"+this.host+":"+this.port);
            }
            System.out.println("connect successfu...ftp服务器:"+this.host+":"+this.port);
        }catch (MalformedURLException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }*/
    /**
     * 删除图片
     */
    public static void delImages(String imagesName){
        try {
            ChannelSftp sftp = getChannel();
            String path = "";
            if(imagesName.contains(rootPath)){
                path =  imagesName;
            }else{
                path = rootPath + imagesName;
            }
            sftp.rm(path);
            sftp.quit();
            sftp.exit();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //文件下载
    public static void  down(String remoteFileUrl, String saveFileName,  HttpServletResponse response)throws  Exception {
        HttpURLConnection conn = null;
        OutputStream oputstream = null;
        InputStream iputstream = null;
        BufferedInputStream bis = null;
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(saveFileName.getBytes("UTF-8"), "iso8859-1"));
        try {
            URL url = new URL(imgUrl+ remoteFileUrl);
            // 将url以open方法返回的urlConnection连接强转为HttpURLConnection连接(标识一个url所引用的远程对象连接)
            // 此时cnnection只是为一个连接对象,待连接中
            conn = (HttpURLConnection) url.openConnection();
            // 设置是否要从 URL连接读取数据,默认为true
            conn.setDoInput(true);
            // 建立连接
            // (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
            conn.connect();
            // 连接发起请求,处理服务器响应 (从连接获取到输入流)
            iputstream = conn.getInputStream();
            File fiule=new File("");

            // 创建文件输出流，用于保存下载的远程文件
            bis = new BufferedInputStream(iputstream);

            oputstream = response.getOutputStream();
            //  用来存储响应数据
            byte[] buffer = new byte[4 * 1024];
            int i = bis.read(buffer);
            int byteRead = -1;
            //  循环读取流
            while(i != -1){
                oputstream.write(buffer);
                i = bis.read(buffer);
            }
            //  输出完成后刷新并关闭流
            oputstream.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                //  重要且易忽略步骤 (关闭流,切记!)
                if (iputstream != null) {
                    iputstream.close();
                }
                if (oputstream != null) {
                    oputstream.close();
                }
                // 销毁连接
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 返回保存后的文件路径
    }
  /**文件传字符串
   * **/
  public static String   ftpFileToString(String remoteFileUrl)throws  Exception {
      HttpURLConnection conn = null;
      OutputStream oputstream = null;
      InputStream iputstream = null;
      BufferedInputStream bis = null;
      String str="";
      try {
          URL url = null;
          if(remoteFileUrl.contains(imgUrl)){
              url= new URL( remoteFileUrl);
          }else{
              url= new URL(imgUrl + remoteFileUrl);
          }


          // 将url以open方法返回的urlConnection连接强转为HttpURLConnection连接(标识一个url所引用的远程对象连接)
          // 此时cnnection只是为一个连接对象,待连接中
          conn = (HttpURLConnection) url.openConnection();
          // 设置是否要从 URL连接读取数据,默认为true
          conn.setDoInput(true);
          // 建立连接
          // (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
          conn.connect();
          // 连接发起请求,处理服务器响应 (从连接获取到输入流)
          byte[] bytes = new byte[0];
          iputstream = conn.getInputStream();
          bytes = new byte[iputstream.available()];
          iputstream.read(bytes);
          str = new String(bytes);


      } catch (Exception e) {
          e.printStackTrace();
      } finally {
          try {
              //  重要且易忽略步骤 (关闭流,切记!)
              if (iputstream != null) {
                  iputstream.close();
              }
              if (oputstream != null) {
                  oputstream.close();
              }
              // 销毁连接
              if (conn != null) {
                  conn.disconnect();
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      // 返回保存后的文件路径
      return str;
  }
  /*//处理附件预览图
    public   String handelerEnclosurePreview(String enclosureUrl) throws Exception {
        String[] split = enclosureUrl.split("\\.");
        if(split[split.length-1].equals("pdf")){
            return enclosureUrl;
        }
        String datePath = new org.joda.time.DateTime().toString("/yyyyMMdd/");
        HttpURLConnection conn = null;
        OutputStream oputstream = null;
        InputStream iputstream = null;
        URL url = new URL(imgUrl+enclosureUrl);
        File file=new File("");
        // 将url以open方法返回的urlConnection连接强转为HttpURLConnection连接(标识一个url所引用的远程对象连接)
        // 此时cnnection只是为一个连接对象,待连接中
        conn = (HttpURLConnection) url.openConnection();
        // 设置是否要从 URL连接读取数据,默认为true
        conn.setDoInput(true);
        byte[] bs = new byte[1024];
        // 建立连接
        // (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
        conn.connect();
        // 连接发起请求,处理服务器响应 (从连接获取到输入流)
        String tempFileName = UUID.randomUUID().toString();

        iputstream = conn.getInputStream();
        String tempPdfPath=getTempFilePath();
        File newFile = new File(tempPdfPath);//转换之后文件生成的地址
        if (!newFile.exists()) {
            newFile.mkdirs();
        }
       // String path="/usr/local/"+tempFileName+"."+split[split.length-1];
        String path=getTempFilePath()+tempFileName+"."+split[split.length-1];
        OutputStream os = new FileOutputStream(path);
        //

        // 开始读取
        int len;
        while ((len = iputstream.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        File file1 = new File(path);//需要转换的文件

        try {
            converter.convert(file1).to(new File(tempPdfPath+"/"+tempFileName+".pdf")).execute();
            //使用response,将pdf文件以流的方式发送的前段

            InputStream in = new FileInputStream(new File(tempPdfPath+"/"+tempFileName+".pdf"));// 读取文件
            FtpUtil.putImages(in,datePath, datePath+tempFileName+".pdf");
           // String tempPdfPath="/usr/local/tempPdf";

       *//*     Thread thread = new Thread(()->{
                try{
                    converter.convert(file1).to(new File(tempPdfPath+"/"+tempFileName+".pdf")).execute();
                    //使用response,将pdf文件以流的方式发送的前段

                    InputStream in = new FileInputStream(new File(tempPdfPath+"/"+tempFileName+".pdf"));// 读取文件
                    FtpUtil.putImages(in,datePath, datePath+tempFileName+".pdf");
                }catch (Exception e){
                    e.printStackTrace();
                }
            },"T2");

            thread.setDaemon(true);
            thread.start();*//*

        } catch (Exception e) {
            e.printStackTrace();
        }
        return datePath+tempFileName+".pdf";
    }*/
}